#source("startup.R")
source("eigenvector.R")
source("oneVersusAll.R")

#k <- 100
#e <- getEigenVect(A%*%t(A),k)
#labels <- getIndividualBinaryLabels(people, TrainingData)

#project the data
projectedDataMatrix = matrix(numeric(0), 0, k)
#for (i in 1:NCOL(A)){
#  projectedDataMatrix = rbind(projectedDataMatrix, project(A[,i], e))
#}

learnNaiveBayes <- function(trnx,trny,param) {
  print("learning")
  model <- list()
  model$probY <- rep(0,NROW(trny))
  model$meanXgivenY <- matrix(0,NROW(trnx),NROW(trny)) 
  model$stdevXgivenY <- matrix(0,NROW(trnx),NROW(trny))
  for(i in 1:NROW(trny)) { #for each person
    ind <- trny[i,] == TRUE
    relx <- trnx[,ind]
    model$probY[i] <- NCOL(relx)/NCOL(trnx)
    for(j in 1:NROW(trnx)) { #for each feature in x
      model$meanXgivenY[j,i] <- mean(relx[j,])
      model$stdevXgivenY[j,i] <- sd(relx[j,])
    }
  }
  return(model)
}

predictNaiveBayes <- function(testx,model) {
  probXgivenY <- matrix(model$probY)
  for(i in 1:length(model$probY)) {
    power <- (testx-model$meanXgivenY[,i])^2/2/(model$stdevXgivenY[,i])^2
    power[is.nan(power)] <- Inf
    prob <- (exp(-power)/model$stdevXgivenY[,i])
    prob[is.nan(prob)] <- 1e10
    probXgivenY[i] <- probXgivenY[i]*prod(prob)
  }
  if(sum(probXgivenY)==0) {
    res <- rep(FALSE,length(model$probY))
    res[1] <- TRUE
    return(res)
  }
  return(probXgivenY == max(probXgivenY))
}

#evaluate
#model <- learnNaiveBayes(t(projectedDataMatrix),labels,c())
#print("evaluating")
#errors <- 0
#for(i in 1:NCOL(A)) {
#  if(0 != sum((predictNaiveBayes(projectedDataMatrix[i,],model) -labels[,i])^2)) {
#    errors <- errors + 1
#  }
#}
#print(errors)

#should pick argmax_y P(Y=y|X=x)
#by bayes rule, P(Y=y|X=x) = P(Y=y)*P(X=x|Y=y)/P(X=x)
#assume x components independent = P(Y=y)*P(x_1|Y)*P(x_2|Y)*...*P(x_n|Y)/P(X=x)
#which is proportional to P(Y=y)*P(x_1|Y)*P(x_2|Y)*...*P(x_n|Y)
